<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\api\service\Message as MessageService;

use think\Request;

class Activity extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'activity';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
        $member_levelMdl = model('Memberlevel');
        $member_level = $member_levelMdl->where('status',1)->field('id,name')->select();

        $member_couponMdl = model('coupon');
        $member_coupon = $member_couponMdl->where('status',1)->field('id,name')->select();

        $this->assign('member_coupon',$member_coupon);
        $this->assign('member_level',$member_level);
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $request = $this->request;
        $param = $request->param();
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            // 排序条件
            $order = '';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            if($this->defaultOrder){
                $order = $this->defaultOrder;
            }
            $fields = 'a.id,a.name,f_name,start_time,end_time,a.create_date,m.name as mName';
            $data = $model->alias('a')
                ->join('member_level m','a.coupon_purpose = m.id')
                ->where($where)
                ->limit($start, $length)
                ->field($fields)
                ->order($order)
                ->select();
            foreach($data as $k => $v)
            {
                $v['key'] = $k + 1;
                $v['start_time'] = substr($v['start_time'],0,10);
                $v['end_time'] = substr($v['end_time'],0,10);
            }
            $count = $model->alias('a')->join('member_level m','a.coupon_purpose = m.id')->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return self::show($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * Add
     */
    public function add(Request $request)
    {
        return parent::add($request);
    }

    /*
     * addPost
     * */
    public function addPost(Request $request, $redirect = '')
    {
        $data = $request->param();
        $model = model('activity');
        $error = $this->checkparam($data);
        if($error['code'] != 0){
            return $this->error($error['msg']);
        }
        if (!empty($data['coupon_id'])){
            $data['coupon_id'] = implode(',',$data['coupon_id']);
        }
        if (!empty($data['pro_id'])){
            $data['pro_id'] = implode(',',$data['pro_id']);
        }
        if (!empty($data['is_coupon'])){
            $data['is_coupon'] = 1;
        }else{
            $data['is_coupon'] = 2;
            unset($data['coupon_id']);
        }
        if (!empty($data['is_product'])){
            $data['is_product'] = 1;
        }else{
            $data['is_product'] = 2;
            unset($data['pro_id']);
        }

        if (!empty($data['id'])){
            //修改
            $time = $model->where(['id'=>$data['id']])->field('create_date')->find();
            $result = $model->where(['id'=>$data['id']])->delete();
            if (!$result){
                return $this->error('修改失败');
            }
            $data['create_date'] = $time['create_date'];
            $data['update_date'] = date('Y-m-d H:i:s',time());
            $result = $model->create($data,true);

            $logInfo = $this->admin->name . '修改了一条' . lang($this->model) . '数据。';

            if($result !== false) {
                // Query执行后的操作
                $model->_after_update($data);

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success('添加成功！', 'admin/promotion/index');
            } else {

                return $this->error($model->getError());
            }
        }else{
            //新增
            $data['create_date'] = date('Y-m-d H:i:s',time());
            $data['id'] = Helper::getUUID();
            $result = $model->create($data,true);
            if (!$result){
                return $this->error('添加失败');
            }
            //添加消息推送
            $addActivity = $this->addActivityMessage($data);
            if (!$addActivity){
                return $this->error($model->getError());
            }
            $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';

            if($result !== false) {
                // Query执行后的操作
                $model->_after_update($data);

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success('添加成功！', 'admin/promotion/index');
            } else {

                return $this->error($model->getError());
            }
        }
    }

    public function addActivityMessage($data)
    {
        //添加活动消息
        $messageMdl = model('message_activity');
        $memberMdl = model('member');
        //所有会员
        if ($data['coupon_purpose'] == 1){
            $memberIds = $memberMdl->column('id');
            foreach($memberIds as $id){
                $messageDate = [
                    'activity_id' => $data['id'],
                    'member_id' => $id
                ];

                $result = $messageMdl->create($messageDate,true);
            }
        }else{
            //指定会员等级
            $memberIds = $memberMdl->where('member_level_id',$data['coupon_purpose'])->column('id');
            if ($memberIds) {
                foreach($memberIds as $id){
                    $messageDate = [
                        'activity_id' => $data['id'],
                        'member_id' => $id
                    ];
                    $result = $messageMdl->create($messageDate,true);
                }
            }
        }

        if (isset($result) && $result !== false) {
            $cid_list = $memberMdl->whereIn('id', $memberIds)->column('c_id');
            // 推送送APP消息
            $mesData = [
                'template_type' => 1,
                'template_data' => [
                    'transmission_type' => 1,
                    'transmission_content' => '',
                    'title' => $data['name'],
                    'text' => $data['f_name'],
                    'logo'  => '',
                    'logo_url'  => '',
                ],
                'cid' => '', // 推送通知至指定用户时填写
                'cid_list' => $cid_list, // 推送通知至指定用户列表时填写
            ];
            MessageService::pushActivity($mesData);
            return true;
        }
    }

    /*
     * editPost
     * */
    public function edit(Request $request)
    {
        $param = $request->param();
        $model = model($this->model);
        if (empty($param['id'])){
            return $this->error('未接收到id');
        }
        $id = $param['id'];

        $info = $model->find($id);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        if (!empty($info['coupon_id'])){
            $info['coupon_id'] = explode(',',$info['coupon_id']);
            $info['coupon_count'] = count($info['coupon_id']);
        } else {
            $info['coupon_id'] = [];
            $info['coupon_count'] = '';
        }
        $product = [];
        if (!empty($info['pro_id'])){
            $info['pro_id'] = explode(',',$info['pro_id']);
            $productMdl = model('product');
            foreach($info['pro_id'] as $v)
            {
                $product[] = $productMdl->where('id',$v)->field('id,name')->find();
            }
        }
        $info['product'] = $product;

        return $this->show($this->editView, [
            'info' => $info
        ]);
    }

    //选择优惠商品
    public function get_product()
    {
        return $this->fetch();
    }

    //渲染商品
    public function get_product_list()
    {
        $productMdl = model('product');
        $where = [
            'a.status' => ['neq', 0],
            'a.type' => ['neq', 3],
            'a.is_gift' => 2
        ];
        $fields = 'a.id,a.name,a.bar_code,a.store_count,a.price,p.name as typeName';
        $data = $productMdl->alias('a')
            ->where($where)
            ->join('product_category p','a.category_id = p.id')
            ->field($fields)
            ->select();
        $result = [
            'code' => '0',
            'msg' => '请求成功',
            'data' => $data,
        ];
        return json($result);
    }

    //验证规则
    private function checkparam($param)
    {
        if (empty($param['title_url'])){
            $error['code'] = '400019';
            $error['msg'] = '封面图为空!';
            return $error;
        }
        if (empty($param['detail_url'])){
            $error['code'] = '400020';
            $error['msg'] = '内页图为空!';
            return $error;
        }
        if (empty($param['name'])){
            $error['code'] = '400021';
            $error['msg'] = '活动标题为空!';
            return $error;
        }
        if (empty($param['f_name'])){
            $error['code'] = '400022';
            $error['msg'] = '活动负标题为空!';
            return $error;
        }
        if (empty($param['coupon_purpose'])){
            $error['code'] = '400022';
            $error['msg'] = '推送对象为空!';
            return $error;
        }

        if (empty($param['is_coupon']) && empty($param['is_product'])){
            $error['code'] = '400025';
            $error['msg'] = '优惠券与商品必须选择一个';
            return $error;
        }

        if (!empty($param['is_product'])){
            if (empty($param['pro_id'])){
                $error['code'] = '400026';
                $error['msg'] = '商品内容不能为空!';
                return $error;
            }
        }

        if (!empty($param['is_product'])){
            if (count($param['pro_id']) != count(array_unique($param['pro_id']))) {
                $error['code'] = '400026';
                $error['msg'] = '商品重复!';
                return $error;
            }
        }

        if ($param['start_time'] == $param['end_time']){
            $error['code'] = '400027';
            $error['msg'] = '开始时间不能等于结束时间!';
            return $error;
        }

        if (strtotime($param['start_time']) > strtotime($param['end_time'])){
            $error['code'] = '400027';
            $error['msg'] = '开始时间不能小于结束时间!';
            return $error;
        }

        $error['code'] = 0;
        $error['msg'] = '';
        return $error;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['a.name'] = ['like', '%'.$param['name'].'%'];
        }
        if(isset($param['level_id']) && $param['level_id']){
            $where['m.id'] = $param['level_id'];
        }

        return $where;
    }

    private function show($template, $data = []) {

        return $this->view->fetch($template, $data);
    }
}
